
package com.sailboard.iot.opm.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.rmi.CORBA.Util;

import com.github.pagehelper.PageInfo;
import com.sailboard.iot.opm.common.Constants;
import com.sailboard.iot.opm.common.DataGrid;
import com.sailboard.iot.opm.common.JsonResult;
import com.sailboard.iot.opm.common.ResultCode;
import com.sailboard.iot.opm.dao.entity.Role;
import com.sailboard.iot.opm.dao.entity.User;
import com.sailboard.iot.opm.service.UserService;
import com.sailboard.iot.opm.service.impl.RoleService;
import com.sailboard.iot.opm.utils.StringUtils;
import com.sailboard.iot.opm.utils.Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by xuejt on 2015/4/3.
 */
@Controller
@RequestMapping(value = "/")
public class UserController {

    @Resource
    UserService userService;
    @Resource
    RoleService roleService;
    private User getCurrent_user(){
        User current_user=new User();
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser != null && currentUser.getPrincipals() != null) {
            String username = currentUser.getPrincipals().toString();
            current_user = userService.getByUsername(username);
        }
        return current_user;
    }

    @RequestMapping(value = "v1/api0/user/list")
    @ResponseBody
    public DataGrid<User> userList(Integer page, Integer rows, User user) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        User current_user=getCurrent_user();
        if(getCurrent_user()!=null){
            user.setCompanyId(current_user.getCompanyId());
        }
        PageInfo pageInfo = userService.getUserList(page, rows, user);
        return new DataGrid(pageInfo);
    }


    @RequestMapping(value = "v1/api0/user/add")
    @ResponseBody
    public JsonResult add(User user) {
        if(user == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(!Utils.checkMobile(user.getMobile())){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "手机号格式错误");
        }
        user.setMobile(user.getMobile().trim());
        if(userService.getUserByMobile(user.getMobile()) != null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该手机号已存在，请重新输入");
        }
        user.setUsername(user.getMobile());//手机号作为用户名。
        String password = "111111";
        String salt = Utils.generateSalt();
        user.setSalt(salt);
        user.setPassword(Utils.encryptPassword(salt, password));
        User current_user=getCurrent_user();
        if(current_user!=null) {
            user.setCompanyId(current_user.getCompanyId());
            user.setCompanyName(current_user.getCompanyName());
        }
        boolean isSuccess = userService.addUser(user);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }


    @RequestMapping(value = "v1/api0/user/edit")
    @ResponseBody
    public JsonResult edit(User user) {
        if(user == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(!Utils.checkMobile(user.getMobile())){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "手机号格式错误");
        }
        user.setMobile(user.getMobile().trim());
        if(userService.getOtherUserByMobile(user.getMobile(),user.getId()) != null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该手机号已存在，请重新输入");
        }
        user.setUsername(user.getMobile());//手机号作为用户名。
        boolean isSuccess = userService.updateUser(user);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    @RequestMapping(value = "v1/api0/user/delete", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete(String ids) {
        if(StringUtils.isEmpty(ids)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }

        boolean isSuccess = userService.batchDelUser(ids);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    @RequestMapping(value = "v1/api0/user/enable", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult enable(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = userService.updateUserStatus(id, Constants.USER_STATUS_ENABLE);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    @RequestMapping(value = "v1/api0/user/disable", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult disable(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = userService.updateUserStatus(id, Constants.USER_STATUS_DISABLE);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    @RequestMapping(value = "v1/api0/user/password/reset", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult resetPassword(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }

        User user = new User();
        user.setId(id);
        String salt = Utils.generateSalt();
        user.setSalt(salt);
        user.setPassword(Utils.encryptPassword(salt, "111111"));

        boolean isSuccess = userService.updateUser(user);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }


    @RequestMapping(value = "v1/api0/user/bindRole", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult bindRole(Long userId, String roleIds) {
        if(userId == null || userId <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        return userService.bindRole(userId, roleIds);
    }

    /*@RequestMapping(value = "v1/api0/user/batchBindRole", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult batchBindRole(String userIds, String roleIds) {
        if(StringUtils.isEmpty(userIds)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        return userService.batchBindRole(userIds, roleIds);
    }*/

    @RequestMapping(value = "v1/api0/user/roles", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult userRoles(Long userId) {
        if(userId == null || userId <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        List<Role> list = roleService.getUserRoles(userId);
        return new JsonResult<>(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG, list);
    }
    @RequestMapping(value = "v1/api0/user/editpwd")
    @ResponseBody
    public JsonResult editPwd(Long userid,String password,String newpassword,String surepassword) {
        if(userid == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.UPDATPWD_NULLID_MSG);
        }
        if(StringUtils.isBlank(password)||StringUtils.isBlank(newpassword)||StringUtils.isBlank(surepassword)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "修改数据为空");
        }
        User user= userService.getUser(userid);
        if(user!=null && !StringUtils.isBlank(user.getPassword())){
            String userpassowrd = user.getPassword().trim();
            String salt =user.getSalt();
            String ecpwd=Utils.encryptPassword(salt, password);
            if(!userpassowrd.equals(ecpwd)){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "旧密码输入错误");
            }
            if(!newpassword.equals(surepassword)){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "两次密码输入不一致");
            }
            user.setPassword(Utils.encryptPassword(salt, newpassword));
        }else{
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "用户状态异常");
        }
        boolean isSuccess = userService.updateUser(user);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }
}
